var spawn = require("child_process").spawn;
const iconv = require('iconv-lite');
const encoding = 'gbk';
const binaryEncoding = 'binary';

module.exports = function myTest(cmd = "ipconfig", cb, param={}) {
    return new Promise(function(resolve, reject) {
        try{
            const fs = require('fs')
            var pathutil = require("path")
            console.log("__dirname: "+__dirname)
            var preloadpath = pathutil.join(__dirname, '../../../../res/adb/adb.exe')
            console.log("preloadpath1: "+preloadpath)

            if (!fs.existsSync(preloadpath)) {
                preloadpath = pathutil.join(__dirname, '../../res/adb/adb.exe')
                console.log("preloadpath2: "+preloadpath)
            }

            preloadpath = preloadpath.replace(/\\(.*?[ ].*?)\\|\/(.*?[ ].*?)\//g,"/\"$1$2\"/")

            var path = preloadpath;
            if(param.devname){
                cmd = cmd.replace(/^adb/g,"adb -s "+param.devname)
                cmd = cmd.replace(/&adb/g,"&adb -s "+param.devname)
            }
            if(param.type=="adb"){
                cmd = cmd.replace(/^adb/g,path)
                cmd = cmd.replace(/&adb/g,"&"+path)
            }
            console.log("cmd: "+cmd)
            var isSucc = false;
            var result = spawn('cmd.exe', ['/s', '/c', cmd]);
            result.on('close', function(code) {
                // code   0:正常  1:报错
                // console.log('child process exited with code :' + code);
            });
            result.stdout.on('data', function(data) {
                isSucc = true;
                // var str = data.toString();
                // var str = (Buffer.from(data.buffer)).toString()
                // var str = iconv.decode(new Buffer(data.buffer, binaryEncoding), encoding)
                var str = iconv.decode(Buffer.from(data.buffer, binaryEncoding), encoding)
                // console.log('stdout: ' + str);
                if(cb){
                    cb(true,str+"  \r\n"+cmd )
                }
            });
            result.stderr.on('data', function(data) {
                if(isSucc) return;
                var str = iconv.decode(Buffer.from(data.buffer, binaryEncoding), encoding)
                // console.log('stderr: ' + str);
                if(cb){
                    cb(false,str+"  \r\n"+cmd)
                }
                reject(new Error(str));
            });
            resolve();
        }catch(ex){
            if(cb){
                cb(false,"指令执行异常:"+ex.message)
                reject(new Error(ex.message));
            }
        }

    });
};